<template>
  <view class="container">
    <view class="header-wrap">
      <view class="tab-box">
        <view class="tags">
          <view v-for="(item,index) in SubsectionList" :key="index" @click="sectionChange(item)" class="tag-view"
            :class="{'active': item===curNow}">
            {{item}}
          </view>
        </view>
        <view class="search-box" @click="showPopClick">
          <text>更多查询</text>
          <image :src="filterIcon" style="width: 20px;height:20px" />
        </view>
      </view>
    </view>
    <view v-if="saleShow" class="top-search">
      <uni-easyinput prefixIcon="search" maxlength="50" v-model="search.name" placeholder="请选择客户"
        @click.native="openSelectSearch" disabled="true">
      </uni-easyinput>
      <button @click="resetSearch">重置</button>
    </view>
    <view v-if="saleShow" class="ovewview">
      <view>
        <view class="label">现金</view>
        <view class="value"><text>{{overview.cashBalanceTotal || '0.00'}}</text>元</view>
      </view>
      <view>
        <view class="label">承兑</view>
        <view class="value"><text>{{overview.acceptanceBalanceTotal || '0.00'}}</text>元</view>
      </view>
    </view>
    <view class="goods-list">
      <view v-if="saleShow" class="item" @click.prevent="goToSaleDetail(item)" v-for="(item, index) in goodsData"
        :key="index" style="margin-bottom: 10px">
        <sale-waybill :itemList="item" :confirmAudit="confirmAudit" :confirmCancel="confirmCancel"
          :orgNameShow="orgNameShow" @cancelWaybill="cancelWaybill" @confirmExamine="confirmExamine"></sale-waybill>
      </view>
      <view v-if="purchaserShow" class="item" @click="goToDetail(item)" v-for="(item, index) in goodsData" :key="index"
        style="margin-bottom: 10px;">
        <goods-number :itemList="item" :hasPermission="hasPermission" :hasPermissionCancel="hasPermissionCancel"
          @showButton="showButton" @cancelPurOrder="openCancelPop"></goods-number>
      </view>
      <uni-load-more :status="pageParams.isMore" />
    </view>
    <waybill-search ref="waybillSearchRef" :show="popShow" :curNow="curNow" :list="stateList" @filterChange="sureClick"
      @closePop="popShow=false"></waybill-search>
    <examine-form :show="isShowPop" :auditDataObj="auditDataObj" :parentId="wayBillId" :cusId="customerId" @closePop="isShowPop = false" :showOneyear="showOneyear"
      @examineCancel="examineCancel" @examinePass="examinePass"></examine-form>
    <select-search ref="selectSearchRef" :show="isShowSearchPop" :type="'radio'" :name="'cusName'" :value="'cusId'"
      :dataLists="customerList" :param="search.id" @search="searchCustomerFn" @cancel="cancelSelectFn"
      @submit="submitCustomerFn"></select-search>
    <cancel-confirm :popId="popId" :show="isShowCancelPop" @cancel="cancelForm" @success="successForm"></cancel-confirm>
  </view>
</template>
<script>
  import { getCoalCustomer } from '@/api/sale.js';
  import { getBasisDeploy } from "@/api/system/user.js"
  import { getTotalBalance } from "@/api/customerAccount"
  import { getDictDatas, getPurIds } from "@/api/transport.js"
  import cancelConfirm from "../common/cancelConfirm/cancelConfirm.vue"
  import { dictTansParams, toast, getButtonShow } from '@/utils/common.js';
  import { getCoalLists, confirmReceipt, cancelPurOrderApi } from "@/api/me.js"
  import { getOrderLists, getSaleWaybillPage, editSaleWaybill,getPlanFromWhere } from "@/api/tranplan.js"
  import { getTenantId, getOpenId, getDriverId, getAccountIdentity } from '@/utils/auth';
  import config from '@/config'
  export default {
    components: {
      cancelConfirm
    },
    data() {
      return {
        showOneyear: false,
        popId: undefined,
        orgNameShow: false,
        SubsectionList: [],
        curNow: '',
        hasPermission: false,
        hasPermissionCancel: false,
        goodsData: [],
        colors: '#409eff',
        popShow: false,
        auditDataObj: {},
        statusDatas: [],
        coaltypeDatas: [],
        stateList: [],
        statusName: '请选择状态',
        rangeKey: ['label'],
        statusChange: [],
        index2: 0,
        queryParam: {
          carBrand: undefined,
          carCard: undefined,
          enterId: undefined,
          proName: undefined,
          waybillStatus: undefined,
          userId: undefined,
          current: 1,
          pageSize: 10
        },
        saleQueryParam: {
          pageNo: 1,
          pageSize: 10,
          customerId: undefined,
          vehicleNo: undefined,
          coalSubtypeName: undefined,
          waybillStatus: undefined,
          smallProgramType: 1
        },
        pageParams: {
          isMore: 'more'
        },
        search: {
          id: undefined,
          name: undefined
        },
        confirmReceiptParam: {
          orderId: undefined,
          userId: undefined,
        },
        proId: undefined,
        titleLists: [
          {
            id: 1,
            text: '待审核',
            checked: true,
          },
          {
            id: 2,
            text: '流程中',
            checked: false,
          },
          {
            id: 3,
            text: '已作废',
            checked: false,
          }
        ],
        isShowPop: false,
        wayBillId: undefined,
        customerId: undefined,
        isShowSearchPop: false,
        isShowCancelPop: false,
        customerList: [],
        cacheCustomerList: [],
        overview: {},
        confirmAudit: false,
        confirmCancel: false
      }
    },
    computed: {
      filterIcon() {
        return config.baseImgUrl + '/more-fliter.png';
      },
      purchaserShow() {
        return !getAccountIdentity() || getAccountIdentity() === 0
      },
      saleShow() {
        return getAccountIdentity() === 1
      }
    },

    methods: {
      cancelSelectFn() {
        this.isShowSearchPop = false
      },
      searchCustomerFn(keyword) {
        this.customerList = this.cacheCustomerList.filter(e => e.cusName.includes(keyword))
      },
      submitCustomerFn(value) {
        this.search = {
          id: value.cusId,
          name: value.cusName
        }
        this.saleQueryParam.customerId = this.search.id
        this.querySaleData()
        this.isShowSearchPop = false
      },
      clearSearchData() {
        this.search = {
          id: undefined,
          name: undefined
        }
        this.saleQueryParam.customerId = undefined
        this.$refs.selectSearchRef?.resetData()
      },
      resetSearch() {
        this.clearSearchData()
        this.querySaleData()
      },
      querySaleData() {
        this.goodsData = []
        this.saleQueryParam.pageNo = 1
        this.pageParams.isMore = 'more'
        this.getTotalBalance()
        this.getSaleWaybillPage()
      },
      openSelectSearch() {
        this.customerList = JSON.parse(JSON.stringify(this.cacheCustomerList))
        this.isShowSearchPop = true
      },
      examineCancel() {
        this.goodsData = []
        this.isShowPop = false
        this.pageParams.isMore = 'more'
        this.saleQueryParam.pageNo = 1;
        this.getSaleWaybillPage()
        toast('审核作废成功');
      },
      async getCoalCustomer() {
        const res = await getCoalCustomer()
        if (res.code === 0) {
          this.cacheCustomerList = res.data || []
          this.customerList = JSON.parse(JSON.stringify(this.cacheCustomerList))
        }
      },
      sectionChange(item) {
        this.pageParams.isMore = 'more'
        this.curNow = item;
        this.resetFun()
        this.getbuttonAuth()
        this.$refs.waybillSearchRef?.resetFilter()
        if (this.saleShow) {
          this.goodsData = []
          this.saleQueryParam.pageNo = 1
          if (this.curNow === '待审核') {
            this.saleQueryParam.waybillStatus = 0
          } else {
            this.saleQueryParam.waybillStatus = undefined
          }
          this.getSaleWaybillPage()
        }
        if (this.purchaserShow) {
          this.queryParam.current = 1
          if (this.curNow == '待确认') {
            this.queryParam.waybillStatus = 4
          } else {
            this.queryParam.waybillStatus = undefined
          }
          this.getDatas();
        }
      },
      changeClick(arr) {
        // 适配小程序 样式需要在父级改变
        this.classList = arr;
      },
      showPopClick() {
        this.popShow = true;
      },
      hideright() {
        this.popShow = false;
      },
      sureClick(datas) {
        this.popShow = false;
        this.pageParams.isMore = 'more'
        if (this.saleShow) {
          this.goodsData = []
          this.saleQueryParam.pageNo = 1;
          this.saleQueryParam.vehicleNo = datas.carBrand
          this.saleQueryParam.coalSubtypeName = datas.proName
          if (this.curNow === '待审核') {
            this.saleQueryParam.waybillStatus = 0
          } else {
            this.saleQueryParam.waybillStatus = datas.waybillStatus
          }
          this.getSaleWaybillPage()
        }
        if (this.purchaserShow) {
          this.queryParam.current = 1
          this.queryParam.carBrand = datas.carBrand
          if (this.curNow == '待确认') {
            this.queryParam.waybillStatus = 4
          } else {
            this.queryParam.waybillStatus = datas.waybillStatus
          }
          this.queryParam.carCard = datas.carCard
          this.queryParam.proName = datas.proName
          this.getDatas();
        }
      },
      async showButton(item) {
        this.confirmReceiptParam.orderId = item.id
        this.confirmReceiptParam.userId = getDriverId()
        let res = await confirmReceipt(this.confirmReceiptParam)
        if (res.code == 200) {
          uni.showToast({
            title: '确认收货成功',
            icon: 'success',
            success: () => {
              setTimeout(() => {
                this.queryParam.current = 1
                this.getDatas();
              }, 1000);
            }
          });
        } else {
          uni.showToast({
            title: '收货失败',
            icon: 'failed'
          });
        }
      },
      openCancelPop(id) {
        this.popId = id
        this.isShowCancelPop = true
      },
      cancelForm() {
        this.isShowCancelPop = false
      },
      successForm() {
        this.queryParam.current = 1
        this.getDatas();
        this.isShowCancelPop = false
      },
      changeCoaltype(e) {
        this.coaltypeDatas.forEach(item => {
          if (item.value == e) this.queryParam.proName = item.text
        })
      },
      async getCoalList() {
        let list = await getPurIds(getDriverId())
        let res = await getCoalLists(list.data)
        if (res.code == 200) {
          this.coaltypeDatas = res.data.map(item => {
            return {
              value: item.proId,
              text: item.proName
            }
          })
        }
      },
      resetFun() {
        this.queryParam.carBrand = undefined
        this.queryParam.proName = undefined
        this.queryParam.waybillStatus = undefined
        this.queryParam.carCard = undefined
        this.saleQueryParam.customerId = undefined
        this.saleQueryParam.vehicleNo = undefined
        this.saleQueryParam.coalSubtypeName = undefined
        this.saleQueryParam.waybillStatus = undefined
        this.statusName = "请选择状态"
      },
      searchData() {
        this.queryParam.current = 1
        this.getDatas();
        this.$refs['searchPopup'].close();
      },
      examinePass() {
        this.goodsData = []
        this.isShowPop = false
        this.pageParams.isMore = 'more'
        this.saleQueryParam.pageNo = 1;
        this.getSaleWaybillPage()
        toast('审核通过成功');
      },
      async cancelWaybill(data) {
        const res = await editSaleWaybill(data)
        if (res.code === 0) {
          this.goodsData = []
          this.pageParams.isMore = 'more'
          this.saleQueryParam.pageNo = 1;
          this.getSaleWaybillPage()
          toast('取消运单成功');
        } else {
          toast(res.msg);
        }
      },
      async confirmExamine(item) {
        console.log("点击了审核按钮")
        this.wayBillId = item.id
        this.customerId = item.customerId
        const resPlan = await getPlanFromWhere(item.planNo)
        if (resPlan.code == 200) {
          if (resPlan.data.whetherSalePlan) {
            this.auditDataObj = {
              addressData: [{'value': resPlan.data.addressId, 'text': resPlan.data.addressName}],
              proData: [{ 'value': resPlan.data.productId, 'text': resPlan.data.productName }],
              relId: resPlan.data.relId
            }
          }
        }
        this.isShowPop = true
      },
      goToSaleDetail(item) {
        uni.navigateTo({
          url: `/packageB/pages/waybill/saleDetails?id=${item.id}`
        });
      },
      goToDetail(item) {
        uni.navigateTo({
          url: `/packageB/pages/waybill/details?id=${item.id}`
        });
      },
      statChange(e) {
        this.index2 = e.detail.value;
        this.statusName = this.stateList[this.index2].label
        this.queryParam.waybillStatus = e.detail.value
      },
      close(ref) {
        this.$refs[ref].close();
      },
      searchMore() {
        this.$refs['searchPopup'].open();
      },
      async getbuttonAuth() {
        //调用公共方法
        this.hasPermission = await getButtonShow('confirmReceipt')
        this.hasPermissionCancel = await getButtonShow('confirmCancel')
        this.confirmAudit = await getButtonShow('purchase-waybill:confirmAudit')
        this.confirmCancel = await getButtonShow('purchase-waybill:cancel')
      },
      async getDatas() {
        this.queryParam.userId = getDriverId()
        let res = await getOrderLists(this.queryParam)
        if (res.code == "200") {
          if (this.queryParam.current == 1) {
            this.goodsData = res.data.rows
          } else {
            this.goodsData = [...this.goodsData, ...res.data.rows]
          }
          if (res.data.total == this.goodsData.length) {
            this.pageParams.isMore = 'noMore';
          } else {
            this.pageParams.isMore = 'more';
          }
        } else {
          this.goodsData = []
          this.pageParams.isMore = 'noMore'
        }
        //停止下拉刷新
        wx.hideNavigationBarLoading();
        //停止下拉刷新
        wx.stopPullDownRefresh();
      },
      async getTotalBalance() {
        const data = {
          tenantId: getTenantId(),
          userId: getDriverId(),
          smallProgramType: 1,
        }
        if (this.search.id) {
          data['customerId'] = this.search.id
        }
        const res = await getTotalBalance(data)
        if (res.code === '200') {
          this.overview = res?.data
        } else {
          toast(res.msg)
        }
      },
      async getSaleWaybillPage() {
        let res = await getSaleWaybillPage(this.saleQueryParam);
        if (res.code === 0) {
          const result = res.data?.list || [];
          const total = res.data?.total || 0;
          this.goodsData = [...this.goodsData, ...result]
          if (total == this.goodsData.length) {
            this.pageParams.isMore = 'noMore';
          } else {
            this.pageParams.isMore = 'more';
          }
        }
        wx.hideNavigationBarLoading();
        wx.stopPullDownRefresh();
      },
      async getDictLists() {
        const datas = await getDictDatas()
        let res = null;
        if (this.saleShow) {
          res = await dictTansParams(datas.data, 'sale_waybill_status')
        }
        if (this.purchaserShow) {
          res = await dictTansParams(datas.data, 'purchase_waybill_status')
        }
        this.stateList = res.map(item => {
          return {
            value: item.value,
            text: item.text
          }
        })
      }
    },
  async onShow() {
      this.isShowPop = false
      let res = await getBasisDeploy(getTenantId())
      if (res.code == 200) {
        this.orgNameShow = res?.data?.isEnabledOrganization === 1 ? true : false
        if (res?.data?.percentageOfPerformance == null) {
          this.showOneyear = false
        } else {
          this.showOneyear = true
        }
      }
      if (this.saleShow) {
        this.SubsectionList = ['待审核', '全部']
        this.curNow = '待审核'
      }
      if (this.purchaserShow) {
        this.SubsectionList = ['待确认', '全部']
        this.curNow = '全部'
      }
      this.isShowCancelPop = false;
      this.popShow = false;
      this.getbuttonAuth()
      this.clearSearchData()
      this.getDictLists()
      this.getCoalCustomer()
      this.getTotalBalance()
      this.sectionChange(this.curNow)
    },
    onPullDownRefresh() {
      this.pageParams.isMore = 'more'
      this.getbuttonAuth()
      if (this.saleShow) {
        this.goodsData = []
        this.saleQueryParam.pageNo = 1;
        this.getSaleWaybillPage()
      }
      if (this.purchaserShow) {
        this.queryParam.current = 1
        this.getDatas()
      }
    },
    onReachBottom() {
      if (this.pageParams.isMore == 'more') {
        if (this.saleShow) {
          this.saleQueryParam.pageNo++;
          this.getSaleWaybillPage()
        }
        if (this.purchaserShow) {
          this.queryParam.current++;
          this.getDatas()
        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  .container {
    .goods-list {
      padding: 20rpx;
    }

    .multi-box {
      border: 1px solid #ccc;
      border-radius: 3px;
      height: 30px;
      line-height: 30px;
      padding: 0 3px;
    }

    .container-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 15px;
    }

    .subsection {
      margin-right: 10px;
    }
  }

  .header-wrap {
    height: 36px;
    font-size: 15px;
    background: #fff;
    border-bottom: 1px solid #E6E6E6;

    .tab-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #E6E6E6;
    }

    .search-box {
      display: flex;
      align-items: center;
      color: #333333;
      margin-right: 10px;

      >text {
        position: relative;
        top: -1px;
      }

      >image {
        width: 20px;
        height: 20px;
      }
    }
  }

  .tags {
    display: flex;
    height: 36px;
    padding: 0 16px;
    line-height: 36px;
    text-align: center;

    .tag-view+.tag-view {
      margin-left: 20px;
    }

    .tag-view {
      width: 45px;
      cursor: pointer;
      color: #333333;
      padding-bottom: 20px;
    }

    .tag-view.active {
      color: #409eff;
      border-bottom: 2px solid #409eff;
    }
  }

  .top-search {
    padding: 10px;
    display: flex;
    align-items: center;
    background-color: #ffffff;
    border-bottom: 1px solid #F1F2F5;

    input {
      flex: 1;
      height: 30px;
      line-height: 30px;
      padding: 0 10px;
      border-radius: 4px;
      margin-right: 20rpx;
      background-color: #F1F2F5;
    }

    button {
      margin-left: 10rpx;
    }
  }

  .ovewview {
    display: flex;
    justify-content: space-between;


    >view {
      width: 50%;
      height: 70px;
      padding: 12px 0;
      border-radius: 4px;
      margin: 10px 10px 0 10px;
      background: linear-gradient(180deg, #dceeff, #ffffff 100%);

      .label {
        text-align: center;
        font-size: 15px;
        color: #333333;
        padding-bottom: 6px;
      }

      .value {
        text-align: center;
        font-size: 14px;
        color: #666666;
      }

      text {
        color: #F78600;
        font-size: 20px;
        font-weight: 600;
      }
    }

    >view+view {
      margin-left: 10px;
    }
  }
</style>